/*
 * WhileInstruction.java
 * 
 * last update: 16.01.2010 by Stefan Saru
 * 
 * author:	Power(power@kermit.cs.pub.ro)
 * 
 * Obs:
 */

package engine;

@SuppressWarnings("serial")
class WhileInstruction extends DefaultInstruction{
	Expression e;
	DefaultInstruction body;

	WhileInstruction(NameSpace ns, int db, InstructionDescription desc,
			Expression e, DefaultInstruction body,
			DefaultInstruction next){
		super(ns, db, desc);
		this.e = e;
		this.body = body;
		if(body != null)
			body.append(this);
		add(next);
	}

	public Instruction next() {
		switch (state) {
		case 1:
			if (body != null)
				return body;
			return this;
		case 2:
			state = 0; //loop
			return next;
		}
		throw new Error("illegal instruction state");
	}

	// isTrue am bagat-o eu in BitVector... presupun ca se va folosi getBoolean()
	// waitToRun() e in DefaultInstruction.java... include delayBefore-ul.
	public void execute()
	throws InterpretTimeException, SimulationStoppedException
	{
		switch (state) {
		case 0:
			waitToRun();
			xConsole.trace(toString());
			state = 1;
			break;
		case 1:
			try{
				boolean cont = e.evaluate().isTrue();
				xConsole.trace(this + " >>> " + cont);
				if(!cont)state = 2;
			}catch(InterpretTimeException ex){
				xConsole.dumpStack(ex);
				throw new InterpretTimeException(desc + ": error:" + ex);
			}
			break;
		}
	}
}
